<script>
// #ifdef H5
import pageAnimation from "@/uni_modules/page-animation";
// #endif
import { mapGetters } from "vuex";

export default {
  // #ifdef H5
  mixins: [pageAnimation],
  // #endif
  computed: {
    ...mapGetters(["token", "userInfo"]),
  },
	globalData: {
		websocketTimer: '', // websocket心跳检测定时器
		reconnectWebSocketTimer: '', // 断线重连定时器（没连接上会一直重连，设置延迟避免请求过多）
		thoroughBreak: false, // 是否禁止断开重开
	},
  onPageNotFound() {
    // 页面不存在监听函数
    uni.redirectTo({
      url: `pages/error/error?type=notfound`,
      animationType: "pop-in",
      animationDuration: 200,
    });
  },
  onError() {
    // 当 uni-app 报错时触发
    uni.redirectTo({
      url: `pages/error/error?type=error`,
      animationType: "pop-in",
      animationDuration: 200,
    });
  },
  onLaunch: function () {
    console.log("应用初始化完成");
    uni.hideTabBar(); // 隐藏底部tabbar
    this.token && this.$store.dispatch("user/GetInfo"); // 有token初始化时刷新用户信息/聊天组信息

		// 建立socket连接
		this.token && this.createWebSocket()
		// $emit $on通信回调
		uni.$on('createWebSocket', () => { // 点击登录后创建websocket
			this.createWebSocket()
		})
		uni.$on('closeWebsocket', () => { // 退出登录 禁止重连
			getApp().globalData.thoroughBreak = true
			this.closeWebsocket()
		})
		// uni.$on('sendWebsocketMessage', (data) => {})
  },
  onShow: function () {
    console.log("应用显示");
  },
  onHide: function () {
    console.log("应用隐藏");
  },
	methods: {
		// 创建websocket
		createWebSocket() {
			getApp().globalData.thoroughBreak = false
			try {
				uni.connectSocket({ url: `${this.VUE_APP.base_ws_URL}/websocket?id=${this.userInfo.userId}&userType=user` })
				this.initWebSocket() // 初始化回调方法
			} catch (error) {
				this.reconnectWebSocket() // 重连websocket
			}
		},
		// 初始化websocket回调方法
		initWebSocket() {
			//监听socket连接
      uni.onSocketOpen(res => {
        console.log('WebSocket连接已打开！')
				// 打开后开始心跳检测
				this.startHeartCheck() // 心跳检测开始
      })
			//监听收到消息
      uni.onSocketMessage(({ data }) => {
        console.log('收到服务器内容：', JSON.parse(data))
				this.resetHeartCheck() // 收到消息后重置心跳检测，再次开始检测
      })
			//监听socket连接失败
      uni.onSocketError(res => {
        console.log('WebSocket连接打开失败，请检查！')
				this.reconnectWebSocket()
      })
      //监听socket关闭
      uni.onSocketClose(res => {
        console.log('WebSocket 已关闭！')
				!getApp().globalData.thoroughBreak && this.reconnectWebSocket()
      })
		},
		// 重连websocket
		reconnectWebSocket() {
			// 避免重复请求连接
			if (getApp().globalData.reconnectWebSocketTimer) {
				return
			}
			getApp().globalData.reconnectWebSocketTimer = setTimeout(() => {
				// 先关闭socket连接再重连
        uni.closeSocket({
          complete: () => {
            this.createWebSocket()
						clearTimeout(getApp().globalData.reconnectWebSocketTimer)
						getApp().globalData.reconnectWebSocketTimer = ''
          }
        })
			}, 5000)
		},
		// 心跳检测 (与服务端约定好消息格式)
		// 服务端响应后30秒后发送检测是否断开
		startHeartCheck() {
			getApp().globalData.websocketTimer = setTimeout(() => {
				const data = JSON.stringify({ id: this.userInfo.userId, userType: 'user', messageType: 'system' })
				uni.sendSocketMessage({	data })
			}, 30000)
		},
		// 心跳检测重置
		resetHeartCheck() {
			clearTimeout(getApp().globalData.websocketTimer)
			getApp().globalData.websocketTimer = ''
			this.startHeartCheck() // 清除后再次开始发送心跳
		},
		// 关闭websocket
		closeWebsocket() {
			console.log('收到关闭websocket')
			uni.closeSocket()
		}
	},
};
</script>

<style lang="scss">
/* 引入uView库样式 */
@import "@/uni_modules/uview-ui/index.scss";
page {
  background-color: #ebebeb;
  color: $u-main-color;
}
:root {
  --bgColor: #ebebeb;
}
/*  项目基础样式 */
@import "@/utils/app.scss";
/* 公共基础样式 */
// 登录页面背景
.login-bg {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
}
</style>
